package com.frame.work.frame.deal;

import com.alibaba.fastjson.JSON;
import com.frame.work.entity.TblZigbeeDeviceProperty;
import com.frame.work.mqtt.Topic;
import com.frame.work.mqtt.data.handle.MqttDataHandle;
import com.frame.work.service.impl.TblZigbeeDevicePropertyService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 人体红外感应面板感应时间配置回应mqtt
 *
 * @author wjming
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Device1015FrameDeal {
    private final MqttDataHandle mqttDataHandle;
    private final TblZigbeeDevicePropertyService zigbeeDevicePropertyService;
    private final RedisTemplate redisTemplate;

    public void deal(String gatewayMac, String data) {
        //设备的网关地址
        String zigbeeMac = StringUtils.substring(data, 2, 18);
        String dataType = StringUtils.substring(data, 0, 2);
        String state = StringUtils.substring(data, data.length() - 2, data.length());

        Map<String, Object> map = new HashMap<>(4);
        map.put("type", "human/infrared/send");
        map.put("zigbeeMac", zigbeeMac);
        //写回复命令。02为写成功回复；82为写失败回复
        map.put("dataType", dataType);
        //命令回复。00为成功，其他为失败。
        map.put("state", state);
        Object time = redisTemplate.opsForValue().get("com.zyzn.infrared.time." + gatewayMac);
        if (time != null) {
            String[] split = StringUtils.split((String) time, "_");
            TblZigbeeDeviceProperty zigbeeDeviceProperty = new TblZigbeeDeviceProperty();
            Map<String, Object> por = new HashMap<>(1);
            por.put("time", split[1]);
            zigbeeDeviceProperty.setId(split[0]);
            zigbeeDeviceProperty.setProperty(JSON.toJSONString(por));
            zigbeeDevicePropertyService.saveOrUpdate(zigbeeDeviceProperty);
        }

        mqttDataHandle.mqttPush(Topic.device.topics + gatewayMac + "/human/infrared/receive", JSON.toJSONString(map));
    }

}
